package com.hooper.iot.face.handler;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.hooper.iot.constants.MsgTypeConstants;
import com.hooper.iot.face.components.ChannelRepository;
import com.hooper.iot.resource.constant.UnifyDeviceTypeNum;
import com.hooper.iot.resource.entity.DeviceFeignRes;
import com.hooper.iot.resource.service.UnifyDeviceService;
import com.hooper.iot.util.IdUntil;
import com.hooper.iot.viid.dto.SubscribeDTO;
import com.hooper.iot.viid.service.ViidService;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import static io.netty.handler.codec.http.HttpUtil.isKeepAlive;
import static io.netty.handler.codec.http.HttpUtil.setContentLength;


/**
 * 实现心跳的hander  支持超时断开客户端避免浪费资源
 *
 * @author WANGCHENG
 */
@Component(value = "serverHeartHandler")
@ChannelHandler.Sharable
@Slf4j
public class ServerHeartHandler extends ChannelInboundHandlerAdapter {
    /**
     * 设置6秒检测chanel是否接受过心跳数据
     */
    private static final int READ_WAIT_SECONDS = 6;
    /**
     * 定义客户端没有收到服务端的pong消息的最大次数
     */
    private static final int MAX_UN_REC_PING_TIMES = 3;
    private final AttributeKey<String> clientInfo = AttributeKey.valueOf("clientInfo");
    private final ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(2, Integer.MAX_VALUE, 5, TimeUnit.SECONDS, new ArrayBlockingQueue<>(1000));
    /**
     * 失败计数器：未收到client端发送的ping请求
     */
    private int unRecPingTimes = 0;
    private WebSocketServerHandshaker handshaker;
    @Resource(name = "channelRepository")
    private ChannelRepository channelRepository;
    @Value("${tcp.host}")
    private String host;
    @Value("${tcp.port}")
    private String port;

    @Resource
    private ViidService viidService;

    @Resource
    private UnifyDeviceService unifyDeviceService ;

    /**
     * 空闲触发器 心跳基于空闲实现
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            String type = "";
            if (event.state() == IdleState.READER_IDLE) {
                type = "read idle";
            } else if (event.state() == IdleState.WRITER_IDLE) {
                type = "write idle";
            } else if (event.state() == IdleState.ALL_IDLE) {
                type = "all idle";
            }
            log.info("设备超过10s未连接=================>" + ctx.channel().remoteAddress());
            if (unRecPingTimes >= MAX_UN_REC_PING_TIMES) {
                // 连续超过N次未收到client的ping消息，那么关闭该通道，等待client重连
                log.debug(ctx.channel().remoteAddress() + "超时类型：" + type);
                //TODO 超过最大次数移除远程连接,默认3，应该给每个连接设置单独的计数器，否则计数器是失效的
                channelRepository.remove(ctx.channel().remoteAddress().toString().substring(1, ctx.channel().remoteAddress().toString().indexOf(":")));
                //重新置为0
                unRecPingTimes = 0;
                ctx.channel().close();
            } else {
                // 失败计数器加1
                unRecPingTimes++;
            }

        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 传统的 HTTP 接入
        if (msg instanceof FullHttpRequest) {
            poolExecutor.submit(() -> {
                try {
                    handleHttpRequest(ctx, (FullHttpRequest) msg);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

        }
        // WebSocket 接入
        else if (msg instanceof WebSocketFrame) {
            handleWebSocketFrame(ctx, (WebSocketFrame) msg);
        }
        ctx.writeAndFlush("next");
        ctx.fireChannelRead(msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        Attribute<String> attr = ctx.attr(clientInfo);
        String clientId = attr.get();
        log.info("捕获到异常，" + clientId + "----错误详情是======" + cause.getMessage());
        cause.printStackTrace();
    }

    private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) {
        // 如果 HTTP 解码失败, 返回HTTP异常
        if (!req.getDecoderResult().isSuccess() || (!"websocket".equalsIgnoreCase(req.headers().get("Upgrade")))) {
            return;
        }
        // 构造握手响应返回
        WebSocketServerHandshakerFactory wsFactory =
                new WebSocketServerHandshakerFactory(host + ":" + port, null, false);
        handshaker = wsFactory.newHandshaker(req);
        if (handshaker == null) {
            WebSocketServerHandshakerFactory.sendUnsupportedWebSocketVersionResponse(ctx.channel());
        } else {
            handshaker.handshake(ctx.channel(), req);
        }
        log.info("远程客户端接入===>" + ctx.channel().remoteAddress().toString());
        channelRepository.put(ctx.channel().remoteAddress().toString().substring(1, ctx.channel().remoteAddress().toString().indexOf(":")), ctx.channel());
    }

    private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {
        // 判断是否是关闭链路的指令
        if (frame instanceof CloseWebSocketFrame) {
            handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
            return;
        }

        // 判断是否是 ping 信息
        if (frame instanceof PingWebSocketFrame) {
            ctx.channel().write(new PongWebSocketFrame(frame.content().retain()));
            return;
        }

        // 本例程仅支持文本消息, 不支持二进制消息
        if (!(frame instanceof TextWebSocketFrame)) {
            throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass().getName()));
        }

        // 返回应答信息
        String request = ((TextWebSocketFrame) frame).text();
        JSONObject object = JSONObject.parseObject(request);
        //对注册返回信息
//        if (object.containsKey(MsgTypeConstants.MSG_TYPE) && object.get(MsgTypeConstants.MSG_TYPE).equals(MsgTypeConstants.REGISTER)) {
//            ctx.channel().write(new TextWebSocketFrame(request + " , 欢迎使用 Netty WebSocket 服务, 现在时刻: "
//                    + new java.util.Date().toString()));
//        }
        if (object.containsKey(MsgTypeConstants.MSG_TYPE)) {
            String msgType = (String) object.get(MsgTypeConstants.MSG_TYPE);
            if(msgType.equals(MsgTypeConstants.HEART_BEAT)){
                log.info("设备心跳=======>"+request);
                JSONObject body = new JSONObject();
                body.put("callType","HEART_BEAT");
                body.put("code",2000);
                body.put("callMsgId", IdUntil.getMessgeId());
                body.put("fileFormat","SOURCE_ID'");
                body.put("platType","ISMP");
                JSONObject rsp = new JSONObject();
                rsp.put("body",body);
                rsp.put("msgId",IdUntil.getMessgeId());
                rsp.put("msgDate",System.currentTimeMillis());
                rsp.put("deviceId",object.getString("deviceId"));
                rsp.put("msgType","SERVER_REQUEST");
                rsp.put("callBack",false);
                ctx.channel().write(new TextWebSocketFrame(rsp.toJSONString()));
            } else if (msgType.equals(MsgTypeConstants.REGISTER)) {
                // 登陆注册，检查设备订阅情况
                String accessId = object.getString("deviceId");
                if (StrUtil.isNotEmpty(accessId)) {
                    // 查询设备信息
                    List<DeviceFeignRes.DeviceData> deviceDatas = unifyDeviceService.query(UnifyDeviceTypeNum.FACE_TERMINAL, accessId);
                    if (CollectionUtil.isEmpty(deviceDatas)) {
                        log.info("订阅失败，一机一档中无设备信息");
                    } else if (deviceDatas.size() > 1) {
                        log.info("订阅失败，存在多个相同的入网ID，请检查");
                    } else if (deviceDatas.size() == 1) {
                        String devId = deviceDatas.get(0).getId();
                        viidService.subscribe(new SubscribeDTO(devId,accessId));
                    }
                }
            }
        }
    }

    private void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
        if (res.getStatus().code() != 200) {
            ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
            System.out.println("buf" + buf);
            res.content().writeBytes(buf);
            buf.release();
            setContentLength(res, res.content().readableBytes());
        }

        // 如果是非 Keep-Alive, 关闭连接
        ChannelFuture f = ctx.channel().writeAndFlush(res);
        if (!isKeepAlive(req) || res.getStatus().code() != 200) {
            f.addListener(ChannelFutureListener.CLOSE);
        }
    }


    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        log.info("channelInactive: client close" + ctx.toString());
        channelRepository.remove(ctx.channel().remoteAddress().toString().substring(1, ctx.channel().remoteAddress().toString().indexOf(":")));
    }
}
